package com.github.netty.service.impl;

import com.github.netty.holder.NettyHolder;
import com.github.netty.service.IMessageSender;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author ArchieSean
 * @description 消息发送服务
 * @date 2024-08-11
 */
@Service
public class MessageSenderImpl implements IMessageSender {

    /**
     * 广播消息
     *
     * @param message 消息内容
     */
    @Override
    public void fanoutMessage(String message) {
        for (Channel channel : NettyHolder.CHANNELS) {
            channel.writeAndFlush(new TextWebSocketFrame(message));
        }
    }

    /**
     * 点对点消息发送
     *
     * @param message 消息内容
     * @param key 接收方链接时所携带的key，比如用户id
     *                点对点消息
     */
    @Override
    public void p2pMessage(String key,String message) {
        if (!StringUtils.hasLength(key)) {
            throw new RuntimeException("接收方，连接key不能为空");
        }
        if (!NettyHolder.CHANNEL_MAP.containsKey(key)) {
            throw new RuntimeException("链接为" + key + "的客户端已断开，不做消息发送");
        }
        Channel channel = NettyHolder.CHANNEL_MAP.get(key);
        channel.writeAndFlush(new TextWebSocketFrame(message));
    }
}
